
React = require('react')
{connect} = require('react-redux')
{View,Accordion,BackAndroid,Animated,Easing,NetInfo,StatusBar,Text,Image,StyleSheet,ScrollView,TouchableOpacity,AsyncStorage} = require('react-native')
Flex = require('antd-mobile/lib/flex')
Button = require('antd-mobile/lib/button')
Icon = require('antd-mobile/lib/icon')
Drawer = require('antd-mobile/lib/drawer')
DrawerLayout = require('react-native-drawer-layout')
List = require('antd-mobile/lib/list')
TimerMixin = require('react-timer-mixin')
Badge = require('antd-mobile/lib/badge')
_ = require('underscore')
# 手风琴在当前版本的antd-design上不可用
# Accordion = require('antd-mobile/lib/accordion')
Item = List.Item
Brief = Item.Brief

InputItem = require('antd-mobile/lib/input-item')
Dimensions = require('Dimensions')
{ width, height } = require('../utilities/getScreen.js')
contentHeight = height - 40
{fetchGetMenu} = require('../actions/menuInfo.js')
{fetchLogin} = require('../actions/userInfo.js')
Toast = require('antd-mobile/lib/toast')
{loginCompleted} = require('../actions/userInfo.js')
{fetchGetList} = require('../actions/page_tz.js')



# _ = require('underscore')
# pxielRatio=PixelRatio.get()

pages =
  game:require('./game.js')
  jkjh:require('./page_inplan.js')
  ckjh:require('./page_outplan.js')
  ybjh:require('./page_moveplan.js')
  jkdd:require('./page_inattemp.js')
  ckdd:require('./page_outattemp.js')
  ybdd:require('./page_moveattemp.js')
  settings:require('./settings.js')
  ckblbb:require('./page_ckblbg.js')
  dddbrz:require('./page_dddbrz.js')
  hdss:require('./page_hdss.js')
  dqdm:require('./page_dqdm.js')
  tz:require('./page_tz.js')
  yhypm:require('./page_yhypm.js')
  gcsj:require('./page_gcsj.js')
  zygg:require('./page_zygg.js')
  tzygg:require('./page_gd.js')
  yhygf:require('./page_yhygf.js')
  ygxlxsq:require('./page_ygxlxcx.js')#已公休轮休查询
  llmtxx:require('./page_mt.js')#浏览码头信息
  gxlxsq:require('./web_gxlxsq.js')
  bwss:require('./page_bwss.js')
  gkcsb:require('./page_gkcsb.js')
  yhsj:require('./page_yhsj.js')
  hxjg:require('./page_hxjg.js')
  ckjl:require('./page_ckjl.js')
  yhyqr:require('./page_yhyqr.js')
  scdzqz:require('./page_scdzqz_list.js')
  eChart : require('./eChart.js')
  dtcxb:require('./web_dtcxb_new.js')
  pilotInfo:require('./page_pilotInfo.js')
icons =
  tzygg:require("../img/icon_gcsj.png")
  zygg:require("../img/icon_gkcsb.png")
  hxjg:require("../img/icon_hdss.png")
  jkjh:require("../img/icon_jkjh.png")
  ckjh:require("../img/icon_ckjh.png")
  ybjh:require("../img/icon_ybjh.png")
  jkdd:require("../img/icon_jkdd.png")
  ckdd:require("../img/icon_ckdd.png")
  ybdd:require("../img/icon_ybdd.png")
  gcsj:require("../img/icon_gcsj.png")
  yhypm:require("../img/icon_yhypm.png")
  yhyqr:require("../img/icon_yhyqr.png")
  dddbrz:require("../img/icon_dddbrz.png")
  gxlxsq:require("../img/icon_gxlxsq.png")
  yhygf:require("../img/icon_yhygf.png")
  hdss:require("../img/icon_hdss.png")
  bwss:require("../img/icon_bwss.png")
  dqdm:require("../img/icon_gcsj.png")
  llmtxx:require("../img/icon_llmtxx.png")
  ygxlxsq:require("../img/icon_ygxlxcx.png")
  ckblbb:require("../img/icon_ckblbg.png")
  scdzqz:require("../img/icon_gcsj.png")
  yhyscks:require("../img/icon_gcsj.png")
  gkcsb:require("../img/icon_gcsj.png")
  ckjl:require("../img/icon_ckjl.png")
  yhsj:require("../img/icon_gcsj.png")
  dtcxb:require("../img/icon_gcsj.png")
  settings:require('../img/icon_sz.png')

MenuItem = require('../components/menuitem.js')
Login = require('./login.js')
backImg = require('../img/forward.png')
menuImg = require('../img/menu.png')
DrawerMenu = require('../components/drawerMenu.js')
Home = React.createClass
  mixins:[TimerMixin]
  getInitialState:->
    @menuIsOpen = false
    rotation: new Animated.Value(0)
  clickHandle:->
    { navigator } = this.props
    navigator.push
        name: 'Second'
        component:Second
  tzClickHandle:->
    {navigator} = @props
    navigator.push
      name:'tz'
      component:pages.tz
      title:"通知"
  loginClickHandle:->
    return if @props.userInfo.pilotCode and @props.userInfo.pilotCode isnt 'guest'
    {navigator} = @props
    navigator.push
      name:'login'
      component:Login
      title:'登陆'

  componentDidMount:->
    that = @
    #若没有本地缓存(首次运行)
    unless @props.userInfo.pilotCode
        @props.dispatch fetchLogin(name:'guest',pass:'')
    #有网络则重新登陆
    debugger
    if @props.connected and @props.userInfo.pilotCode
      @props.dispatch fetchLogin
        name:@props.userInfo.pilotCode
        pass:@props.userInfo.pass
    @props.fetchGet()#取得通知
    @props.fetchGetGongGao()#取得重要公告


    # NetInfo.fetch().done (status)->
    #   if status not in ['NONE','DUMMY','UNKNOWN']
    #     AsyncStorage.getItem('userInfo').then (result)->
    #       debugger
    #       if result
    #         userInfo = JSON.parse result
    #         that.props.dispatch fetchLogin(name:userInfo.pilotCode,pass:userInfo.pass)
    #       else
    #         that.props.dispatch fetchLogin(name:'guest',pass:'')
    #     ,(err)->
    #       debugger
    #       that.props.dispatch fetchLogin(name:'guest',pass:'')
    #     that.props.fetchGet()


    # AsyncStorage.getItem 'userInfo',(err,result)->
    #   if result isnt null
    #     userInfo = JSON.parse result
    #     that.props.dispatch fetchLogin(name:userInfo.pilotCode,pass:userInfo.pass)
    #   else
    #     that.props.dispatch fetchLogin(name:'guest',pass:'')
    # @props.fetchGet()

  componentWillUpdate:(nextProps)->
    # unless nextProps.menuInfo.isLoading
    #   Toast.hide()
  componentDidUpdate:->
    #判断登陆是否成功，成功后获取菜单
    # @refs.scroll.scrollTo {x:0,y:0,animated:true}
    #若有网络则重新加载菜单

  scrollToTop:->
    @refs.scroll.scrollTo {x:0,y:0,animated:false}

  # drawerClickHandle:->
  #   debugger
  #   that = @
  #   if @menuIsOpen
  #     @drawer.drawer.closeDrawer()
  #     @menuIsOpen=false
  #     Animated.timing(@state.rotation,
  #       toValue:1
  #       duration: 300
  #       easing: Easing.linear).start ->
  #         that.setState rotation: new Animated.Value(0)
  #   else
  #     @drawer.drawer.openDrawer()
  #     @menuIsOpen = true
  #     menuIcon = @refs.menuIcon
  #     Animated.timing(@state.rotation,
  #       toValue:-1
  #       duration: 300
  #       easing: Easing.linear).start ->
  #         that.setState rotation: new Animated.Value(0)





  onDrawerOpenChange:(isOpen)->
    # @menuIsOpen = isOpen
    debugger
    drawerMenu = @refs.drawerMenu
    drawerMenu.runAnimate isOpen
    # @forceUpdate()
  exitBtnHandle:->
    BackAndroid.exitApp()
  settingClickHandle:->
    navigator = @props.navigator
    target={name:'settings',component:pages['settings']}
    navigator.push target
  chartBtnClickHandle:->
    navigator = @props.navigator
    target={name:'eChart',component:pages['eChart']}
    navigator.push target
  pilotInfoClickHandle:->
    navigator = @props.navigator
    target={name:'pilotInfo',component:pages['pilotInfo']}
    navigator.push target
  renderSlideBar:->
    # <List renderHeader={() => '菜单'}>
    <View style={{flexDirection:'column',paddingBottom:10, height:contentHeight,backgroundColor:'#ffffff'}}>
      <List renderHeader={() => '菜单'}>
        {
          if @props.userInfo.pilotCode  in ['guest','',null]
            <Item arrow="horizontal" onClick={@settingClickHandle}>
              应用设置
            </Item>
          else
            [<Item arrow="horizontal"  multipleLine onClick={@pilotInfoClickHandle}>
              个人信息
            </Item>
            <Item arrow="horizontal" onClick={@settingClickHandle}>
              应用设置
            </Item>]
      }
      </List>
      <View style={{flex:1}} />
      <List>
          <Item multipleLine extra={<Button size='small' onClick={@exitBtnHandle}  type='warning'>退出应用</Button>}>
            台州港引航站
            <List.Item.Brief>COPYRIGHT BY SHANGHAI PILOT,ALL RIGHTS RESERVED.</List.Item.Brief>
          </Item>
      </List>
    </View>
  openDrawer:->
    debugger
    @refs.drawer.drawer.openDrawer()
  closeDrawer:->
    @refs.drawer.drawer.closeDrawer()
  render:->
    that = @
    # <View style={{alignItems:'center',height:30,paddingTop:5}}>
    #   <Text style={{fontSize:30,color:'#FFFFFF',alignItems:'center'}}>上海港引航站</Text>
    # </View>
    loginImg = require('../img/avatar.png')
    # <View style={{flex:0,alignItems:'center',width:width}}>
    #   <Text style={{fontSize:20,color:'#FFFFFF'}}>上海港引航站</Text>
    # </View>
    #重要公告提醒
    if @props.markRead
      markRead = @props.markRead
    else
      markRead = []
    GongGaokeys = for obj in  @props.GongGaolist[0..19]
                    obj.INNO
    filterKeys = (obj for obj in GongGaokeys when obj not in markRead )
    r = filterKeys.length

    #通知提醒
    tzKeys = for obj in  @props.tz_list[0..19]
                    obj.INNO
    tzFilterKeys = (obj for obj in tzKeys when obj not in markRead )
    tzBadge = tzFilterKeys.length

    if @props.userInfo.token is null
      that.setTimeout ->
        that.scrollToTop()
      ,1000
    <View>
      <DrawerMenu ref="drawerMenu" openDrawer={@openDrawer} closeDrawer={@closeDrawer} />
      <Drawer
          style={{height:contentHeight}}
          ref="drawer"
          drawerWidth={width * 2 / 3}
          drawerPosition={DrawerLayout.positions.Left}
          sidebar={@renderSlideBar()}
          onOpenChange={@onDrawerOpenChange}>
            <View style={styles.mainView}>
              <View style={styles.topView}>
                <Image style={[styles.topImage,{flex:1,resizeMode:'contain'}]}  source={require('../img/headview.png')}>
                  <View  style={styles.topSonView1}>
                    <View style={{width:width / 4,flexDirection:'column',marginLeft:10,justifyContent:'center',alignItems:'center'}} >
                      <TouchableOpacity style={{marginTop:20,width:width / 4,justifyContent:'center',alignItems:'center'}} onPress={@loginClickHandle}>
                        <Image source={loginImg} style={{height:height / 10,width:height / 10,resizeMode:'contain'}}>
                        </Image>
                      </TouchableOpacity>
                      <Text style={{height:20,color:'#ffffff',fontWeight:'bold'}}>
                        {
                          if @props.userInfo?.pilotName isnt '游客'
                             @props.userInfo.pilotName
                          else
                            '登陆'
                        }
                      </Text>
                    </View>
                    <View style={{paddingTop:20,justifyContent:'flex-start',alignItems:'center',flexDirection:'column'}}>
                      <ScrollView>
                        {
                          if @props.userInfo.pilotCode not in ['guest','',null]
                            if tzBadge>0
                              <Badge text={tzBadge} overflowCount={10} style={{marginTop:10}}>
                                <Text style={{color:'#ffffff',marginRight:10}}>
                                  通知  ：
                                </Text>
                              </Badge>
                            else
                              <Text style={{color:'#ffffff',marginRight:10}}>
                                通知  ：
                              </Text>
                        }
                        {
                          if @props.userInfo.pilotCode not in ['guest','',null]
                            do =>
                              list = @props.tz_list[0..2]
                              for m in list
                                <TouchableOpacity onPress={@tzClickHandle} key={m.INNO}>
                                  <View style={{paddingRight:40,width:width*3/4}}>
                                    <Text style={{color:'#ffffff'}}>
                                      {m.VCTITLE}
                                    </Text>
                                  </View>
                                </TouchableOpacity>
                        }
                      </ScrollView>
                    </View>
                  </View>
                  <View style={[styles.topSonView2,{paddingBottom:40}]}>
                    <MenuItem isHeader=true navigator={if @props.userInfo.pilotCode  in ['guest','',null] then null else @props.navigator} key={'zygg'} img={icons.zygg} Badge={r} title='重要公告' target={name:'zygg',component:pages['zygg']} />
                    <MenuItem isHeader=true navigator={@props.navigator} key={'hxjg'} img={icons.hxjg} title='航行警告' target={name:'hxjg',component:pages['hxjg']} />
                    <MenuItem isHeader=true navigator={@props.navigator} key={'yhsj'} img={icons.yhsj} title='引航数据' target={name:'yhsj',component:pages['yhsj']} />
                  </View>
                </Image>
              </View>
              <View style={{height:contentHeight*3/5 - 12}}>
                <ScrollView showsVerticalScrollIndicator={true} bounces={true} alwaysBounceVertical={true}  ref="scroll">
                  <View style={{borderTopWidth:1,borderColor:'#AAAAAA'}}>
                    {
                      do =>
                        debugger
                        return if @props.menuInfo.menuItems.length is 0
                        menus = (v for v in @props.menuInfo.menuItems when v.sortid isnt '0' and v.gnid not in ['yhyscks'])
                        # menus.push {gnid:'settings',gnmc:'设置'}
                        # menus.push {gnid:'dtcxb',gnmc:'动态潮汐表'}
                        for i in [0..menus.length-1] by 3
                          <View key={i} style={styles.bottomSonView}>
                            <MenuItem  key={menus[i].gnid} navigator={@props.navigator}  img={icons[menus[i].gnid]} title={menus[i].gnmc} target={name:menus[i].gnid,component:pages[menus[i].gnid]}/>
                            { if menus[i+1] then <MenuItem key={menus[i+1].gnid}  navigator={@props.navigator} img={icons[menus[i+1].gnid]} title={menus[i+1].gnmc} target={name:menus[i+1].gnid,component:pages[menus[i+1].gnid]}/> else <View key={'unkKey1'} style={{flex:1}}/>}
                            { if menus[i+2] then <MenuItem key={menus[i+2].gnid}  navigator={@props.navigator} img={icons[menus[i+2].gnid]} title={menus[i+2].gnmc} target={name:menus[i+2].gnid,component:pages[menus[i+2].gnid]}/> else <View key={'unkKey2'} style={{flex:1}}/>}
                          </View>
                    }
                  </View>
                </ScrollView>
              </View>
          </View>
        </Drawer>
    </View>



styles = StyleSheet.create
  center:
    alignItems:'center'
    justifyContent: 'center'
  fullScreen:
    width:width
    height:height
  image:
    width:width
    height:height
  mainView:
    width:width
    # height:height
    flex:1
    flexDirection:"column"
  topView:
    width:width
    # height:height*2/5
    alignItems: 'center'
    flexDirection:'column'
    flex:0
    # borderColor:'#ffffff'
    # borderWidth:1
  topImage:
    width:width - 10
    height:contentHeight * 2/5
    # borderColor:'#ffffff'
    # borderWidth:1
  topSonView1:
    width:width
    # backgroundColor:'red'
    flexDirection:'row'
    height:20
    flex:1
  topSonView2:
    alignItems:'flex-start'
    justifyContent:'flex-start'
    width:width
    # backgroundColor:'blue'
    flexDirection:'row'
    flex:1
    # height:20

  bottomSonView:
    width:width
    flexDirection:'row'
    flexWrap:'wrap'
    alignItems:'center'
    justifyContent:'center'
    # borderTopWidth:1
    # borderColor:'#AAAAAA'
  menuImg:
    marginLeft:10
    width:width / 12
    height:width / 12
    resizeMode:'contain'



mapStateToProps = (state)->
  tz_list:state.page_tz.list
  menuInfo:state.menuInfo
  userInfo:state.userInfo
  connected:state.appState.connected
  markRead:state.page_zygg.markRead
  GongGaolist:state.page_zygg.list
mapDispatchToProps = (dispatch,wonProps)->
  dispatch:dispatch
  fetchGet:->
    dispatch fetchGetList(1,'2')#取得通知
  fetchGetGongGao:->
    dispatch fetchGetList(1,'1')#取得重要公告
module.exports = connect(mapStateToProps,mapDispatchToProps)(Home)
